﻿namespace MDK.Device.Components
{
    public interface IFreezerController : IPlcDeviceComponent
    {
        /// <summary>
        /// 下限温度,摄氏度
        /// </summary>
        double LowerLimit { get; set; }
        /// <summary>
        /// 上限温度,摄氏度
        /// </summary>
        double UpperLimit { get; set; }
        double[] GetTemperatures();
    }

    public class FreezerController : IFreezerController
    {
        private PlcAddress _lowerLimitAddr;
        private PlcAddress _upperLimitAddr;
        private PlcAddress[] _curTemperatureAddrs;

        public IPlcDevice Device { get; }

        public FreezerController(IPlcDevice device, PlcAddress lowerLimitAddr, PlcAddress upperLimitAddr, params PlcAddress[] temperatureAddrs)
        {
            Device = device;
            _lowerLimitAddr = lowerLimitAddr;
            _upperLimitAddr = upperLimitAddr;
            _curTemperatureAddrs = temperatureAddrs;
        }

        public double LowerLimit
        {
            get { return ((double) Device.PLC.ReadInt(_lowerLimitAddr)) / 10; }
            set { Device.PLC.WriteInt(_lowerLimitAddr, (int) (value * 10)); }
        }

        public double UpperLimit
        {
            get { return ((double)Device.PLC.ReadInt(_upperLimitAddr)) / 10; }
            set { Device.PLC.WriteInt(_upperLimitAddr, (int)(value * 10)); }
        }

        public double[] GetTemperatures()
        {
            var count = _curTemperatureAddrs == null ? 0 : _curTemperatureAddrs.Length;
            var temps = new double[count];
            for (int i = 0; i < count; i++)
            {
                temps[i] = ((double)Device.PLC.ReadInt(_curTemperatureAddrs[i])) / 10;
            }
            return temps;
        }
    }
}